﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using Common;
using Controllers.Extend;
using Controllers.Filter;
using Model.Sys.Config;
using ViewModel;

namespace Controllers.Areas.UserInfo.Controllers
{
    [Exception]
    public class HomeController : UserBaseController
    {
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            cookieName =CookieConfig.UserInfoLoginCookieName;
            base.OnAuthorization(filterContext);

            if (loginUser == null)
            {
                if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.Result = new JsonResult()
                    {
                        ContentEncoding = Encoding.UTF8,
                        Data = new ResultModel
                        {
                            Pass = false,
                            Msg = "对不起，您的身份验证过时，请重新登录。"
                        },
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                }
                else
                {
                    filterContext.Result = new ContentResult() { Content = "<script>alert('对不起，您的身份验证过时，请重新登录。');top.location='/Login/Index';</script>" };
                }
            }
        }

        /// <summary>
        /// 用户界面
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 用户界面的菜单
        /// </summary>
        /// <returns></returns>
        public ActionResult MenuList()
        {
            List<ZTreeModel> menuList = null;
            List<Model.Database.Power> powerList = new List<Model.Database.Power>();


            foreach (var role in loginUser.Roles)
            {
                powerList.AddRange(role.Powers.ToList()); ;
            }
            foreach (var deparment in loginUser.Departments)
            {
                foreach (var role in deparment.Roles)
                {
                    powerList.AddRange(role.Powers.ToList());
                }
            }
            HashSet<Model.Database.Power> powerSet=new HashSet<Model.Database.Power>(powerList);
            powerList.Clear();
            powerList = powerSet.ToList();
            menuList = MakeMenuList(powerList);

            return Json(menuList);
        }

        /// <summary>
        /// 用户界面的首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Welcome()
        {
            return View();
        }

        /// <summary>
        /// 用户中心的首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Center()
        {
            return View(loginUser);
        }

        /// <summary>
        /// 用户基础信息编辑提交
        /// </summary>
        /// <returns></returns>
        public ActionResult BaseInfoEditSubmit(Model.Database.UserInfo pmUserInfo)
        {
            ResultModel rm = new ResultModel();

            if (string.IsNullOrEmpty(pmUserInfo.Nickname))
            {
                rm.Pass = false;
                rm.Msg = "请填写昵称";
                return Json(rm);
            }
            if (!ValidateHelper.IsValidEmail(pmUserInfo.Email))
            {
                rm.Pass = false;
                rm.Msg = "请填写正确邮箱";
                return Json(rm);
            }
            if (!ValidateHelper.IsCellPhone(pmUserInfo.Phone))
            {
                rm.Pass = false;
                rm.Msg = "请填写正确手机号";
                return Json(rm);
            }
            else
            {
                Model.Database.UserInfo userInfoOld= CurrentBllSession.UserInfoBll.GetEntity(pmUserInfo.UserInfoId);//此处读库，不读缓存，为了防止此时管理员禁用此用户失效
                userInfoOld.Nickname = pmUserInfo.Nickname;
                userInfoOld.Email = pmUserInfo.Email;
                userInfoOld.Phone = pmUserInfo.Phone;
                userInfoOld.QQ = pmUserInfo.QQ;
                userInfoOld.Sex = pmUserInfo.Sex;
                userInfoOld.Birthday = pmUserInfo.Birthday;
                userInfoOld.Age = pmUserInfo.Age;
                userInfoOld.Homeplace = pmUserInfo.Homeplace;
                userInfoOld.Address = pmUserInfo.Address;
                userInfoOld.Hobby = pmUserInfo.Hobby;
                userInfoOld.Sign = pmUserInfo.Sign;
                CurrentBllSession.UserInfoBll.Update(userInfoOld);
                #region 更新缓存中UserInfo信息
                var cookieValue = CookieHelper.GetCookieValue(cookieName);
                if (!string.IsNullOrEmpty(cookieValue))
                {
                    Model.Database.UserInfo userInfoOldCache=CurrentBllSession.CacheBll.GetCache<Model.Database.UserInfo>(cookieValue).Value as Model.Database.UserInfo;//旧缓存
                    if (userInfoOldCache != null)
                    {
                        userInfoOldCache.Nickname = pmUserInfo.Nickname;
                        userInfoOldCache.Email = pmUserInfo.Email;
                        userInfoOldCache.Phone = pmUserInfo.Phone;
                        userInfoOldCache.QQ = pmUserInfo.QQ;
                        userInfoOldCache.Sex = pmUserInfo.Sex;
                        userInfoOldCache.Birthday = pmUserInfo.Birthday;
                        userInfoOldCache.Age = pmUserInfo.Age;
                        userInfoOldCache.Homeplace = pmUserInfo.Homeplace;
                        userInfoOldCache.Address = pmUserInfo.Address;
                        userInfoOldCache.Hobby = pmUserInfo.Hobby;
                        userInfoOldCache.Sign = pmUserInfo.Sign;
                        CurrentBllSession.CacheBll.Update(cookieValue, userInfoOldCache);
                    }
                }
                #endregion
                rm.Pass = true;
                rm.Msg = "保存成功";
                return Json(rm);
            }
        }
        
        /// <summary>
        /// 上传头像
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public ActionResult HeadPhotoUpload(HttpPostedFileBase file)
        {
            ResultModel rm = new ResultModel();

            if (file!=null && file.ContentLength > 0)
            {
                string ext = Path.GetExtension(file.FileName);//扩展名

                if (ext != ".gif" && ext != ".jpg" && ext != ".jpeg" && ext != ".png" && ext != "bmp" && ext != ".ico")
                {
                    rm.Pass = false;
                    rm.Msg = "格式不正确";
                    return Json(rm);
                }
                try
                {
                    CurrentBllSession.UserInfoBll.UpdateHeadPhoto(file, loginUser);
                    rm.Pass = true;
                    rm.Msg = "上传成功";
                    return Json(rm);
                }
                catch (Exception ex)
                {
                    rm.Pass = false;
                    rm.Msg = ex.Message;
                    return Json(rm);
                }
            }
            else
            {
                rm.Pass = false;
                rm.Msg = "空文件";
                return Json(rm);
            }
        }

        /// <summary>
        /// 修改密码提交
        /// </summary>
        /// <returns></returns>
        public ActionResult EditPasswordSubmit(string oldPassword,string newPassword)
        {
            ResultModel rm = new ResultModel();

            if (string.IsNullOrEmpty(oldPassword))
            {
                rm.Pass = false;
                rm.Msg = "请填写旧密码";
                return Json(rm);
            }
            if (string.IsNullOrEmpty(newPassword))
            {
                rm.Pass = false;
                rm.Msg = "请填写新密码";
                return Json(rm);
            }
            else
            {
                if (oldPassword != loginUser.LoginPassword)
                {
                    rm.Pass = false;
                    rm.Msg = "旧密码输入不正确";
                    return Json(rm);
                }
                else
                {
                    loginUser.LoginPassword = newPassword;
                    if (loginUser.IsSuper.HasValue && loginUser.IsSuper.Value)//超级管理员的角色是手动加的，数据库中没有对应记录，更新会报错，所以特别处理
                    {
                        loginUser.Roles.Clear();
                    }
                    CurrentBllSession.UserInfoBll.Update(loginUser);
                    rm.Pass = true;
                    rm.Msg = "修改成功";
                    return Json(rm);
                }
            }
        }

        [Power(PowerId = "02000100")]
        public ActionResult TestPage()
        {
            return View();
        }















        #region 私有方法

        /// <summary>
        /// 手机验证
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private bool IsPhone(string str)
        {
            bool result = false;

            Regex r = new Regex(@"^[1]+[3,5]+\d{9}");
            if (r.IsMatch(str))
            {
                result = true;
            }

            return result;
        }
        /// <summary>
        /// 邮箱验证
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private bool IsEmail(string str)
        {
            bool result = false;

            Regex r = new Regex(@"^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+");
            if (r.IsMatch(str))
            {
                result = true;
            }

            return result;
        }
        /// <summary>
        /// 制作菜单集合
        /// </summary>
        private List<ZTreeModel> MakeMenuList(List<Model.Database.Power> powerList)
        {
            List<Model.Database.Power> treeSortList=new List<Model.Database.Power>();
            List<ZTreeModel> menuList = new List<ZTreeModel>();

            TreeSortList(powerList, treeSortList,"0");
            foreach (var power in treeSortList.Where(a=>a.IsMenu))
            {
                ZTreeModel menu=new ZTreeModel(){id = power.PowerId,pId = power.ParentId,name = power.PowerName};
                if (!string.IsNullOrEmpty(power.Url))
                {
                    menu.url = power.Url+"?powerId=" + power.PowerId;
                }
                menuList.Add(menu);
            }
            if (menuList.Count > 0)
            {
                menuList[0].open = true;
            }

            return menuList;
        }

        /// <summary>
        /// 树状排序集合（递归）
        /// </summary>
        private void TreeSortList(List<Model.Database.Power> powerList, List<Model.Database.Power> treeSortPowerList, string parentId)
        {
            foreach (var power in powerList.Where(a => a.ParentId == parentId).OrderBy(a => a.Sort))//菜单
            {
                treeSortPowerList.Add(power);

                TreeSortList(powerList, treeSortPowerList, power.PowerId);
            }
        }

        #endregion

    }
}
